import time
import csv
from urllib import request

from django.core import serializers
from django.db.models import Sum
from django.http import JsonResponse, HttpResponse
from django.shortcuts import render, redirect
from la import models
import json

# Create your views here.
from la.view.func import ishaveskuandnum, getPID, getDPID


def login(req):
    """登录页面操作"""
    if req.method == "GET":
        form = LoginModelForm()
        return render( req, "login.html", {"form": form} )
    form = LoginModelForm( data=req.POST )
    if form.is_valid():
        print( form.cleaned_data )
        admin = models.userinfo.objects.filter( **form.cleaned_data ).first()
        if not admin:
            form.add_error( "password", "用户名或密码错误" )
            return render( req, 'login.html', {'form': form} )
        info = {'name': admin.name, 'no': admin.no, "level": admin.level, 'isty': admin.isty,
                'storecode': admin.storecode.id}
        req.session["info"] = info

        return redirect( "/la/index" )
    return render( req, 'login.html', {'form': form} )


def index(req):
    """HOME页面操作"""
    day = time.strftime( "%Y-%m-%d", time.localtime() )
    mon = time.strftime( "%Y-%m", time.localtime() )
    info = req.session.get( "info" )
    print( mon )
    dsaleinfo = models.salelist.objects.filter( time__contains=day, store_id=info['storecode'] ).values(
        'store_id' ).annotate( nums=Sum( "num" ), prices=Sum( 'price' ) ).all()
    msaleinfo = models.salelist.objects.filter( time__contains=mon, store_id=info['storecode'] ).values(
        'store_id' ).annotate( nums=Sum( "num" ), prices=Sum( 'price' ) ).all()
    return render( req, "index.html", {"ds": dsaleinfo, "ms": msaleinfo} )


"""基本信息设置"""


def invoice(req):
    """收银台界面"""
    info = req.session.get( "info" )
    sn = getPID( req )
    ''''''
    syrinfos = models.sypeople.objects.filter( store_id=info['storecode'] ).all()
    zffsinfos = models.zffslist.objects.all()
    sname = models.storeinfo.objects.filter( id=info['storecode'] ).first().name
    package = models.package.objects.all()
    if req.method == "GET":
        return render( req, "invoice.html",
                       {"syrinfos": syrinfos, "zffsinfos": zffsinfos, "sn": sn, "sname": sname, "package": package} )
    if (req.method == "POST"):
        '''差一个问题，就是当用户输出两个相同的款号时，默认要分边各减一次，会造成负库存，后期要在前端把验证加进去'''
        pid = req.POST.get( "pid" )
        syr = req.POST.get( "syr" )
        zffs = req.POST.get( "zffs" )
        member = req.POST.get( "member" )
        listre = req.POST.get( "data" )
        listre = json.loads( listre )
        for item in listre:
            print( item )
            sku = item["款号"]
            num = item['数量']
            price = item['价格']
            num2 = models.inventory.objects.filter( sku=item['款号'], num__gte=item['数量'],
                                                    storecode_id=info['storecode'] ).first().num
            nnum = int( num2 ) - int( num )
            if nnum < 0:
                return JsonResponse( {"re": "销售数量大于库存数量"} )
            res = models.salelist.objects.create( sku=sku, num=num, price=price, pid=pid,
                                                  time=time.strftime( "%Y-%m-%d %H:%M:%S", time.localtime() ),
                                                  opid="", syname_id=syr, zffs_id=zffs, store_id=info["storecode"],
                                                  member_id=member )
            '''现在开始写减库存'''
            if member != "":
                points = models.member.objects.filter( id=member ).first().points
                models.member.objects.filter( id=member ).update( points=int( points ) + int( price ) * int( num ) )
            else:
                print( "会员为空" )
            models.inventory.objects.filter( sku=sku, storecode_id=info['storecode'] ).update( num=nnum )
        re = {"re": True}
        return JsonResponse( re )


def invoiceSKU(req):
    """检验SKU的AJAX"""

    info = req.session.get( "info" )
    sku = req.POST.get( "sku" )
    num = req.POST.get( "num" )
    re = models.inventory.objects.filter( sku=sku, num__gte=num, storecode_id=info['storecode'] ).first()
    if re != None:
        re = {"re": True}
    else:
        re = {"re": False}
    return JsonResponse( re )


def invoiceFIND(req):
    """查找退货单明细"""

    info = req.session.get( "info" )
    pid = req.POST.get( "pid" )
    re = models.salelist.objects.values().filter( pid=pid, store_id=info['storecode'], opid="" )
    if re != None:
        j = list( re )
        return JsonResponse( j, safe=False )
    else:
        re = {"re": "未查到单据，或单据已发生退货"}
    return JsonResponse( re )


def invoiceth(req):
    """退货"""
    info = req.session.get( "info" )
    skus = req.POST.getlist( 'data' )
    pid = req.POST.get( "pid" )
    DPID = getDPID( req )
    re = models.salelist.objects.values().filter( pid=pid, store_id=info['storecode'], opid="" ).first()
    syname_id = re['syname_id']
    zffs_id = re['zffs_id']
    for item in skus:
        re = models.salelist.objects.values().filter( pid=pid, store_id=info['storecode'], opid="", sku=item ).first()
        res = models.salelist.objects.create( sku=item, num=0 - int( re['num'] ), price=0 - float( re['price'] ),
                                              pid=DPID,
                                              time=time.strftime( "%Y-%m-%d %H:%M:%S", time.localtime() ),
                                              opid=pid, syname_id=syname_id, zffs_id=zffs_id,
                                              store_id=info["storecode"] )
        models.salelist.objects.filter( pid=pid, store_id=info['storecode'], sku=item ).update( opid=DPID )
        nums = models.inventory.objects.filter( sku=item, storecode_id=info['storecode'] ).first().num
        models.inventory.objects.filter( sku=item, storecode_id=info['storecode'] ).update(
            num=int( re['num'] + int( nums ) ) )
    return JsonResponse( {"re": False} )


def invoiceFINDmemberPhone(req):
    """查找会员明细"""

    info = req.session.get( "info" )
    phone = req.POST.get( "phone" )
    re = models.member.objects.values().filter( phone=phone )
    print( re )
    if re != None:
        j = list( re )
        return JsonResponse( j, safe=False )
    else:
        re = {"re": "未查到单据，或单据已发生退货"}
    return JsonResponse( re )


def invoiceMemberSalePackage(req):
    info = req.session.get( "info" )
    packageName = req.POST.get( "packageName" )
    packagePrice = req.POST.get( "packagePrice" )
    members = req.POST.getlist( 'data' )
    package = models.package.objects.filter( name=packageName ).first()
    packageid = package.id
    times = package.times
    packageInfos = models.packagelist.objects.filter(package_id = packageid).all()
    f = False
    for item in packageInfos:
        num = models.inventory.objects.filter( sku=item.sku, storecode_id=info['storecode'] ).first().num
        if int( item.num ) <= int( num ):
            f = True
    if f:
        for item in members:
            for items in packageInfos:
                num = models.inventory.objects.filter( sku=items.sku, storecode_id=info['storecode'] ).first().num
                models.inventory.objects.filter( sku=items.sku, storecode_id=info['storecode'] ).update(
                    num=int( int( num ) - items.num) )
                #print("循环次数："+str(items.num))
                """判断库存表中是否有SKU没有新建，有更新"""
                n = models.packageInventoryList.objects.filter( storecode_id=info['storecode'], member_id=item,
                                                                sku=items.num).first()
                if n == None:
                    models.packageInventoryList.objects.create( storecode_id=info['storecode'], member_id=item,
                                                                sku=items.sku, num=items.num )
                else:
                    models.packageInventoryList.objects.filter( storecode_id=info['storecode'], member_id=item,
                                                                sku=items.sku ).update(
                        num=int( n.num ) + int( items.num) )
            break
        models.packageSaleList.objects.create( package=packageName, price=packagePrice, member_id=item,
                                                                storecode_id=info['storecode'],times = times )
        re = {"re": "添加成功"}
    else:
        re = {"re": "添加失败，套餐库存不足"}
    return JsonResponse( re )


def salelist(req):
    """销售列表界面"""
    info = req.session.get( "info" )
    sre = None
    if req.method == "POST":
        start = req.POST.get( 'start' ) + " 00:00:00"
        end = req.POST.get( 'end' ) + " 23:59:59"
        sre = models.salelist.objects.filter( store_id=info['storecode'], time__gte=start, time__lte=end )
    return render( req, "sale_info.html", {"re": sre} )


def packagesaleinfo(req):
    """套餐销售列表"""
    if req.method == "GET":
        info = req.session.get( "info" )
        inre = models.packageSaleList.objects.filter( storecode_id=info['storecode'] ).all()
        return render( req, "packagesale_info.html", {"re": inre} )

def packageseek(req,nid):
    """套餐销售明细"""
    if req.method == "GET":
        ps = models.packageSaleList.objects.filter(id=nid).first()
        return render(req,"package_seek.html",{"re":ps})
    info = req.session.get( "info" )
    id = req.POST.get("id")
    times = models.packageSaleList.objects.filter(id=id).first().times
    models.packageSaleList.objects.filter( id=id ).update(times = times-1 )
    re = {"re": "添加成功"}
    return JsonResponse( re )




def exportSalelist(req):
    info = req.session.get( "info" )
    response = HttpResponse( content_type='text/csv' )
    response['Content-Disposition'] = 'attachment; filename="salelist.csv"'
    writer = csv.writer( response )
    writer.writerow( ['款号', '数量', '价格', '单据时间', '收银员', '支付方式'] )
    salelist_info = models.salelist.objects.filter( store_id=info['storecode'] ).all().values_list( 'sku', 'num',
                                                                                                    'price', 'time',
                                                                                                    'syname', 'zffs' )
    for sl in salelist_info:
        writer.writerow( sl )
    return response


from django import forms


class UserInfoModelForm( forms.ModelForm ):
    class Meta:
        model = models.userinfo
        fields = ["name", "no", "password", "level", "storecode"]
        # widgets = {
        #     "name": forms.TextInput(attrs={"class": 'form-control m-b-15'}),
        #     "no": forms.TextInput(attrs={"class": 'form-control m-b-15'}),
        #     "password": forms.TextInput(attrs={"class": 'form-control m-b-15'}),
        #     "level": forms.Select(attrs={"class": 'form-control m-b-15'}),
        #     "storecode": forms.Select(attrs={"class": 'form-control m-b-15'})
        # }

    def __init__(self, *args, **kwargs):
        super().__init__( *args, **kwargs )
        for name, field in self.fields.items():
            # print(name)
            field.widget.attrs = {"class": 'form-control m-b-15'}


class StoreInfoModelForm( forms.ModelForm ):
    class Meta:
        model = models.storeinfo
        fields = ["code", "name"]

    def __init__(self, *args, **kwargs):
        super().__init__( *args, **kwargs )
        for name, field in self.fields.items():
            field.widget.attrs = {"class": 'form-control m-b-15'}


class SkuInfoModelForm( forms.ModelForm ):
    class Meta:
        model = models.skuinfo
        fields = ["sku", "year", "season", "wave", "color", "colorCode", "size", "price", "cost", "type", "brand"]

    def __init__(self, *args, **kwargs):
        super().__init__( *args, **kwargs )
        for name, field in self.fields.items():
            field.widget.attrs = {"class": 'form-control m-b-15'}


class InventoryModelForm( forms.ModelForm ):
    class Meta:
        model = models.inventory
        fields = ['sku', 'num', 'fhnum', 'shnum']

    def __init__(self, *args, **kwargs):
        super().__init__( *args, **kwargs )
        for name, field in self.fields.items():
            field.widget.attrs = {"class": 'form-control m-b-15'}


class LoginModelForm( forms.ModelForm ):
    class Meta:
        model = models.userinfo
        fields = ["no", "password"]

        widgets = {
            "no": forms.TextInput( attrs={"class": 'form-control m-b-15'} ),
            "password": forms.TextInput( attrs={"class": 'form-control m-b-15'} )
        }

        def __init__(self, *args, **kwargs):
            super().__init__( *args, **kwargs )
            for name, field in self.fields.items():
                field.widget.attrs = {"class": 'form-control m-b-15'}
